#!/usr/bin/env python
#coding=utf-8

from __future__ import division
import time
import sys
from define import BASE_DIR
sys.path.append(BASE_DIR)

#import pymongo
from lib.abstract_cron import abstract_cron
from lib.func_ext import str2sec,sec2str,ksort

#需要修改
class api_day(abstract_cron) :

    #需要修改
    #noLock = True   #是否生成脚本锁文件
    selectTable = 'sdb_statistics_api_hour'
    insertTable = 'sdb_statistics_api_day'

    def __init__(self) :
        #需要修改
        super(api_day,self).__init__(__file__)

    def boot(self,timestamp=[]) :
#        self.preBoot()

        sql = self.getSelectSql(timestamp)
        row = self.db.select(sql)

        if row :
            self.writeSql(sql,'succ','select')
            for v in row :
                #数据过滤
                self.filterItems(v)

            #批量插入
            self.doBatchExec()
        else :
            self.writeSql(sql,'fail','select')
        self.sufBoot()
        print 'ok'

    def getSelectSql(self,timestamp=[]) :
        timeFilter = self.getTimeFilter(timestamp)
        sql = 'SELECT `api`,SUM(`sum`) AS sum,SUM(`sum_succ`) AS sum_succ,`date`,`hour` AS call_time FROM '+self.selectTable+' WHERE '+self.db._filter(timeFilter)
        sql += ' GROUP BY `api`'
        return sql

    def getTimeFilter(self,timestamp=[]) :
        keyFilter = {}
        keyFilter['date'] = timestamp and timestamp or (int(sec2str('%Y%m%d',time.time()-1*24*3600)))
        return keyFilter

    def insertKeys(self) :
        return ['api','sum','sum_succ','date','call_time']


#需要修改
if __name__ == '__main__' :
    obj = api_day()
    obj.boot()
